﻿<cffunction name="flexigridstruct" access="public" hint="flexigrid json" description="convert query to flexigrid json">
	
	<cfargument name="query" required="true" type="query" hint="query">
	<cfargument name="columns" required="true" type="string" hint="list of columns of query to show">
	<cfargument name="page" required="true" type="numeric" hint="current flexigrid page">
	<cfargument name="rows" required="true" type="numeric" hint="record per page in flexigrid">
	<cfargument name="key" required="false" type="string" hint="table key, use as flexigrid row id"> 
	
	<!---
		flexigrid json
		
		{
			"total": (total rows),
			"page": (displayed page),
			"rows": [
			{
				"id": (row id),
				"cell": [
					(cell content),
					(cell content),
					(cell content),
					(cell content)
				]
			},
			{
				"id": (row id),
				"cell": [
					(cell content),
					(cell content),
					(cell content),
					(cell content)
				]
			}
			]
		}
	--->
	
	<cfscript>
		local.endRow = arguments.page * arguments.rows;
		local.startRow = local.endRow - arguments.rows + 1; 
		
		local.flexigrid = StructNew();
		
		local.flexigrid["total"] = arguments.query.recordCount;
		local.flexigrid["page"] = arguments.page;
		local.flexigrid["rows"] = ArrayNew(1);
		
		for (i = local.startRow; i lte local.endRow; i++) {
			
			if (i lte arguments.query.recordCount) {			
				local.rows = StructNew();
				if (Len(Trim(arguments.key))) {
					// use query columns with arguments.key name as row id 
					local.rows["id"] = encryptHex(arguments.query[arguments.key][i]); 
				}
				else {
					// use loop sequence
					local.rows["id"] = i;
				}
				
				local.rows["cell"]  = ArrayNew(1);
				
				for (j = 1; j lte ListLen(arguments.columns); j++) {
					local.cell = arguments.query[ListGetAt(arguments.columns, j)][i];
					ArrayAppend(local.rows["cell"], local.cell);
				}
				
				ArrayAppend(local.flexigrid.rows, local.rows);
			}
		}
		
		return local.flexigrid;
	</cfscript>
	
</cffunction>